package com.agger.harmonyosthemeseditor.abilities.slices;

import com.agger.harmonyosthemeseditor.ThemesEditorAbility;
import com.agger.harmonyosthemeseditor.userinterface.*;
import com.agger.harmonyosthemeseditor.intelligent.*;
import com.agger.harmonyosthemeseditor.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.bundle.IBundleManager;
import ohos.eventhandler.EventRunner;
import ohos.global.resource.NotExistException;
import ohos.global.resource.ResourceManager;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.IntentConstants;
import ohos.utils.net.Uri;
import java.io.*;

public class ImageEnhancementSlice extends AbilitySlice
{
    private final int ChooseImage=1001;
    Image showImageArea=null;
    PixelMap pxm = null;
    String Dialog_Title = "爱洁羊智慧能力";
    String Dialog_Content_StoragePermissionFailed = "存储功能被禁用，请前往应用管理页，开启主题协作器的存储权限！";
    String Dialog_Button_Cancel = "取消";
    String Dialog_Button_Confirm = "好的";
    String Toast_NoneImage = "请先选择待处理图象！";
    String Toast_AIEngine_Preparing = "智慧引擎准备中，请稍后再试！";
    String Toast_Image_SaveFinish = "图象已存储至";
    String Toast_Image_SaveFailed = "存储图象时出现错误，请确保设备容量充足！";

    @Override
    public void onStart(Intent intent)
    {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_slice_image_enhancement);
        this.getWindow().setStatusBarColor(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_statusbar_normal,0xF7EDD8));
        this.getWindow().setNavigationBarColor(ResourceTool.getColor(this,ResourceTable.Color_dawnlighti_navigationbar_normal,0xF7EDD8));
        int CurrentColorMode = getColorMode();
        if(CurrentColorMode == 0) this.getWindow().setStatusBarVisibility(0);
        else if(CurrentColorMode == 1) this.getWindow().setStatusBarVisibility(2052);
        ThemesEditorAbility.Instance.eventRunner = EventRunner.current();
        GeneralUtil.setWindowToMaxRefreshRate(getWindow());
        ImageIntelligent.Init(this);
        try
        {
            if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
            {
                if (canRequestPermission("ohos.permission.READ_USER_STORAGE")&&canRequestPermission("ohos.permission.WRITE_USER_STORAGE"))
                    requestPermissionsFromUser(new String[] { "ohos.permission.READ_USER_STORAGE","ohos.permission.WRITE_USER_STORAGE"} ,2);
            }
        }catch(Exception ex){}
        ResourceManager resManager = getResourceManager();
        try
        {
            Dialog_Title = resManager.getElement(ResourceTable.String_Dialog_Title).getString();
            Dialog_Content_StoragePermissionFailed = resManager.getElement(ResourceTable.String_Dialog_Content_StoragePermissionFailed).getString();
            Dialog_Button_Cancel = resManager.getElement(ResourceTable.String_Dialog_Button_Cancel).getString();
            Dialog_Button_Confirm = resManager.getElement(ResourceTable.String_Dialog_Button_Confirm).getString();
            Toast_NoneImage = resManager.getElement(ResourceTable.String_Toast_NoneImage).getString();
            Toast_AIEngine_Preparing = resManager.getElement(ResourceTable.String_Toast_AIEngine_Preparing).getString();
            Toast_Image_SaveFinish = resManager.getElement(ResourceTable.String_Toast_Image_SaveFinish).getString();
            Toast_Image_SaveFailed = resManager.getElement(ResourceTable.String_Toast_Image_SaveFailed).getString();
        }catch (Exception e){}
        pxm = getPixelMapFromResource(ResourceTable.Media_AddPicturesArea);
        showImageArea=(Image)findComponentById(ResourceTable.Id_showImageArea);
        showImageArea.setPixelMap(pxm);
        showImageArea.setClickedListener(c ->
        {
            try{
                if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED || verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED)
                {
                    if (canRequestPermission("ohos.permission.READ_USER_STORAGE")&&canRequestPermission("ohos.permission.WRITE_USER_STORAGE"))
                    requestPermissionsFromUser(new String[] { "ohos.permission.READ_USER_STORAGE","ohos.permission.WRITE_USER_STORAGE"} ,2);
                    else
                    {
                        GeneralDialog.Builder builder = new GeneralDialog.Builder(getContext());
                        builder.setTitle(Dialog_Title)
                                .setContent(Dialog_Content_StoragePermissionFailed)
                                .addButton(Dialog_Button_Cancel, GeneralButtonElement.TYPE_NORMAL, GeneralDialog::remove)
                                .addButton(Dialog_Button_Confirm, GeneralButtonElement.TYPE_ACCENT, this::PermissionRouter)
                                .setOutsideTouchClosable(false)
                                .setMovable(false)
                                .create()
                                .show();
                    }
                }else{selectPic();}
            }catch(Exception ex){}
        });
        Button Button_StartProcess=(Button)findComponentById(ResourceTable.Id_Button_StartProcess);
        int spacingHorizontal = (int) ResourceTool.getFloat(this, ResourceTable.Float_spacing_ui_button, 0);
        Button_StartProcess.setBackground(new GeneralButtonElement(this, GeneralButtonElement.TYPE_UI_Button));
        Button_StartProcess.setTextColor(new Color(ResourceTool.getColor(this, ResourceTable.Color_dawnlighti_button_text_accent, 0xFFFFFF)));
        Button_StartProcess.setMultipleLine(false);
        Button_StartProcess.setTruncationMode(Text.TruncationMode.ELLIPSIS_AT_END);
        Button_StartProcess.setPaddingLeft(spacingHorizontal);
        Button_StartProcess.setPaddingRight(spacingHorizontal);
        Button_StartProcess.setClickedListener(c->
        {
            try
            {
                if(ImageIntelligent.ConnectSuccess)
                {
                    if(showImageArea.getPixelMap()!=null&&showImageArea.getPixelMap()!=pxm)
                    {
                        ProcessImage();
                    }else
                    {
                        new GeneralToast(this).setText(Toast_NoneImage).show();
                    }
                }
                else
                {
                    new GeneralToast(this).setText(Toast_AIEngine_Preparing).show();
                }
            }catch (Exception ex){}
        });
        DisplayAttributes displayAttributes = DisplayManager.getInstance().getDefaultDisplay(this).get().getAttributes();
        showImageArea.setCornerRadius(12f*displayAttributes.scalDensity);
        findComponentById(ResourceTable.Id_actionBar_Back).setClickedListener(c->onBackPressed());
        DatabaseManager.Init(this);
        String Ability_QuitBySelf = DatabaseManager.getString("ImageEnhancementAbility_QuitBySelf","No");
        if(!Ability_QuitBySelf.equals("Yes"))
        {
            String UriString = DatabaseManager.getString("ImageEnhancementAbility_ImageUri","None");
            if(!UriString.equals("None"))
            {
                Uri uri_rec =Uri.parse(UriString);
                PixelMap pixelMap_rec = ImageIntelligent.ObtainImage(uri_rec,this);
                if(pixelMap_rec != null) showImageArea.setPixelMap(pixelMap_rec);
            }
        }
        DatabaseManager.setString("ImageEnhancementAbility_QuitBySelf","No");
    }

    @Override
    public void onBackPressed()
    {
        DatabaseManager.Init(this);
        DatabaseManager.setString("LastAbilityName","None");
        DatabaseManager.setString("ImageEnhancementAbility_QuitBySelf","Yes");
        DatabaseManager.setString("ImageEnhancementAbility_ImageUri", "None");
        try{getWindow().setNavigationBarColor(ResourceTool.getColor(this, ResourceTable.Color_dawnlighti_navigationbar_bottom, 0xF5F1E6));}catch (Exception ex){}
        ThemesEditorAbility.isMainSceneSlice = true;
        try{showImageArea.release();}catch(Exception e){}
        try{pxm.release();}catch(Exception e){}
        showImageArea=null;
        pxm = null;
        Dialog_Title = null;
        Dialog_Content_StoragePermissionFailed = null;
        Dialog_Button_Cancel = null;
        Dialog_Button_Confirm = null;
        Toast_NoneImage = null;
        Toast_Image_SaveFinish = null;
        Toast_Image_SaveFailed = null;
        System.gc();
        if(ThemesEditorAbility.LayoutChanged)
        {
            ThemesEditorAbility.LayoutChanged = false;
            try{MainSceneSlice.Instance.restart();}catch (Exception ex){}
        }
        else
        {
            try{MainSceneSlice.Instance.pageSwiper.ReturnImageSwiper_Industry(true);}catch(Exception ex){}
        }
        super.onBackPressed();
    }

    private PixelMap getPixelMapFromResource(int resourceId) {
        InputStream inputStream = null;
        try{
            inputStream = getContext().getResourceManager().getResource(resourceId);
            ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
            srcOpts.formatHint = "image/png";
            ImageSource imageSource = ImageSource.create(inputStream, srcOpts);
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            return imageSource.createPixelmap(decodingOptions);
        }catch(IOException e){}
        catch(NotExistException e){}
        finally
        {
            if (inputStream != null)
            {
                try {inputStream.close();}
                catch(IOException e){}
            }
        }
        return null;
    }

    public void PermissionRouter(GeneralDialog dialog)
    {
        Intent e = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withAction(IntentConstants.ACTION_APPLICATION_DETAILS_SETTINGS)
                .withUri(Uri.getUriFromParts("package",getBundleName(),null))
                .build();
        e.setOperation(operation);
        startAbility(e);
        dialog.remove();
    }

    private void selectPic() {
        Intent intent = new Intent();
        Operation opt=new Intent.OperationBuilder()
                .withAction("android.intent.action.OPEN_DOCUMENT")
                .withFlags(Intent.FLAG_NOT_OHOS_COMPONENT)
                .build();
        intent.setOperation(opt);
        intent.setType("image/*");
        startAbilityForResult(intent,ChooseImage);
    }

    private void ProcessImage()
    {
        PixelMap pixelMap = showImageArea.getPixelMap();
        int Width = pixelMap.getImageInfo().size.width;
        int Height = pixelMap.getImageInfo().size.height;
        int MaxPixel = Width;
        int MinPixel = Height;
        if(Height>Width)
        {
            MaxPixel = Height;
            MinPixel = Width;
        }
        if(MaxPixel<=1024&&MinPixel<=768)
            ImageIntelligent.saveImage("ImagebyAGI_"+GeneralUtil.getTimeStr(),ImageIntelligent.EnhanceImage(pixelMap,this,true),this,Toast_Image_SaveFinish,Toast_Image_SaveFailed);
        else if(MaxPixel<=1920&&MinPixel<=1080)
            ImageIntelligent.saveImage("ImagebyAGI_"+GeneralUtil.getTimeStr(),ImageIntelligent.EnhanceImage(pixelMap,this,false),this,Toast_Image_SaveFinish,Toast_Image_SaveFailed);
        else
            ImageIntelligent.saveImage("ImagebyAGI_"+GeneralUtil.getTimeStr(),pixelMap,this,Toast_Image_SaveFinish,Toast_Image_SaveFailed);
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData)
    {
        if(requestCode==ChooseImage)
        {
            //放入尝试体内，防止用户未选择图片而造成应用闪退
            try
            {
                String ImageUri=resultData.getUriString();
                Uri targetUri;
                DatabaseManager.Init(this);
                if(ImageUri.contains("externalstorage"))
                {
                    targetUri = resultData.getUri();
                    DatabaseManager.setString("ImageEnhancementAbility_ImageUri", ImageUri);
                }else
                {
                    String ImageId;
                    if(ImageUri.lastIndexOf("%3A")!=-1)ImageId = ImageUri.substring(ImageUri.lastIndexOf("%3A")+3);
                    else ImageId = ImageUri.substring(ImageUri.lastIndexOf('/')+1);
                    targetUri=Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,ImageId);
                    DatabaseManager.setString("ImageEnhancementAbility_ImageUri",targetUri.toString());
                }
                DataAbilityHelper dataAbilityHelper = GeneralUtil.createDataAbilityHelper(this);
                ImageSource imageSource = null;
                try
                {
                    FileDescriptor fd = dataAbilityHelper.openFile(targetUri, "r");
                    imageSource = ImageSource.create(fd, null);
                    PixelMap pixelMap = imageSource.createPixelmap(null);
                    showImageArea.setPixelMap(pixelMap);
                } catch (Exception e) {} finally {if(imageSource!=null)imageSource.release();}
            }catch (Exception e){}
        }
    }

    @Override
    public void onActive() {super.onActive();}

    @Override
    public void onForeground(Intent intent) {super.onForeground(intent);}
}